<template>
	<view class="add-sec-scope-page">
		<view class="map-container">
			<map
			  id="map"   
			  ref="mapRef"
			  :longitude="location.lote"   
			  :latitude="location.late"   
			  :scale="scale"   
			  show-location   
			  :markers="markers"  
			   style="width: 100%; height: 100%;">  
			</map> 
		</view>
 
		<view class="footer">
			<view class="search">
				<uni-search-bar v-model="searchValue" @confirm="search" @clear="clear" placeholder="请输入搜索地址" />
			</view>
			<view class="list" ref="listRef">
				<view v-if="addresList.length > 0">
					<view v-for="(local, index) in addresList" class="address-item" :key="local.id"  @click="() => onTips(local)">
						<view class="title">{{ local.title }}</view>
						<view class="address">{{ local.address }}</view>
					</view>
				</view>
				<view v-else>
					<Empt />
				</view>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { ref, computed, onMounted } from 'vue'
	import { onLoad } from "@dcloudio/uni-app"
	import { mapSdk } from '@/utils/index'; 
	import { homeServer } from "@/common/index"
	import Empt from "@/components/Empt/index.vue"
	import { useStudentListStore } from "@/stores/useStudentList.js"
	import { response } from './list.js'
	import gcoord from '@/utils/gcoord.global.prod.js';
		
	const studentStore = useStudentListStore();
	const currentStudent = computed(() => studentStore.currentStudent)
	const transformLatLon = (longitude, latitude) => {
		const baiduCoord = [longitude, latitude];
		  // 使用 gcoord 将百度坐标转化为腾讯地图坐标
		const tencentCoord = gcoord.transform(
			baiduCoord,
			gcoord.BD09,  // 百度坐标系
			gcoord.GCJ02  // 腾讯地图使用的是国测局坐标系 (GCJ02)
		);
		return tencentCoord;
	}
	
	
	const markers = ref([]);
	const setMarkers = ({title = currentStudent.value?.name, latitude, longitude}) => {
		const marker = {
			// id: Number(data.studentId),  //必须是number类型
			 id:1,
			 latitude: latitude,  
			 longitude: longitude,  
			 width: 50,  
			 height: 50,  
			 iconPath: '/static/images/tabbar/message_active.png', // 自定义图标路径  
			 callout: {
				content: title,
				display: 'ALWAYS', 
				padding: 5  
			 }
		};
		markers.value = [marker]
	}
	
	
	const map = ref(null);
	const location = ref({})
	const scale = ref(15);
	const listRef = ref();
	const mapRef= ref();
	interface AddresListProps{
		ad_info:{
			adcode: number,
			city: string
			district: string
			province: string
		}
		address: string
		category: string
		id: string
		location: {
			lat: number
			lng: number
		},
		tel: string
		title: string
		type: number
		_distance: number
	}
	const addresList = ref<Array<AddresListProps>>([])
	
	const searchValue = ref("");
	const search = async ({value}) =>{
		searchValue.value = value;
		if(location.value?.late && location.value?.lote && value !== ""){
			localtionSearch({keyword: value, late: location.value.late, lote: location.value.lote})
		}
	};
	// 设置围栏
	interface TraceScopesAddProps{
		name: string
		address: string
		latitude:  string
		longitude: string
		warnDistance: string
		startTime?: string
		endTime?: string
	}
	const traceScopesAdd = async ({name, address, latitude, longitude, warnDistance, startTime ="00:00",endTime = "23:59"}: TraceScopesAddProps) => {
		const studentId = currentStudent.value?.id;
		try{
			const {status, data} = await homeServer.traceScopesAdd({studentId, address, latitude, longitude, warnDistance, startTime, endTime, name});
			if(status === '200'){
				uni.showToast({
					title: '添加成功',
					icon:"success",
					success() {
						uni.navigateBack()
					}
				});
			}
		}catch(e){
			//TODO handle the exception
		}
	}
	
	const onTips = (item: AddresListProps) => {
		uni.showModal({
			title:"添加",
			content:`${item.title} 距离 ${item._distance}米`,
			cancelText:"取消",
			confirmText:"确认添加",
			success({confirm}) {
				location.value.late = item.location.lat 
				location.value.lote = item.location.lng
				setMarkers({title: item.title, latitude: item.location.lat, longitude: item.location.lng});
				if(confirm){
					traceScopesAdd({name: item.title, latitude: `${item.location.lat}`, longitude: `${item.location.lng}`, warnDistance: `${item._distance}`, address: `${item.address}${item.title}`})
				}
			}
		})
	}
	
	const input = (res) => {
		console.log('----input:', res)
	};
	const clear = (res) => {
		searchValue.value = ""
	};
	const blur = (res) => {
		uni.showToast({
			title: 'blur事件，输入值为：' + res.value,
			icon: 'none'
		})
	};
	const focus = (e) => {
		uni.showToast({
			title: 'focus事件，输出值为：' + e.value,
			icon: 'none'
		})
	};
	const cancel = (res) => {
		uni.showToast({
			title: '点击取消，输入值为：' + res.value,
			icon: 'none'
		})
	}
	const lateLoteByPrePageSend = ref(); // 存储上个页面发送过来的经纬度
	onLoad(({late,lote}) => {
		console.log("获取到了经纬度",  late, lote)
		const [ LOT, LAT] = transformLatLon(late, lote)
		console.log('几位内毒', LOT, LAT)
		lateLoteByPrePageSend.value = { late: LAT, lote: LOT}
		location.value = {
			late: LOT,
			lote: LAT
		};
		console.log('location.value', location.value)
		setMarkers({latitude: LAT, longitude: LOT});
		localtionSearch({keyword:"江夏", late: LAT, lote: LOT})
	});
	
	// 周边搜索  https://lbs.qq.com/service/webService/webServiceGuide/search/webServiceSearch#2
	const localtionSearch  = async ({keyword = '', late , lote}) => {
		try{
			mapSdk.QQMapSdk.search({
				keyword,
				boundary: `nearby(${late}, ${lote}, 1000,1)`,
				get_subpois: 1,
				page_size: 20,
				page_index: 1,
				success: (res:any) => {
					console.log('查询成功', res)
					const {status, data, message} = res;
					if(status === 0){
						addresList.value = data;
					} else {
						uni.showToast({
							title: message,
							duration:1000,
							icon: "none"
						})
					}
				},
				fail: (res) => {
					console.log('查询失败', res)
					uni.showToast({
						title:"查询失败",
						icon:"error"
					})
				}
			  }
			)
		}catch(e){
			return e;
			//TODO handle the exception
		}
		
	}
	
	onMounted(() => {
		// 创建map对象
		map.value = uni.createMapContext('map');
		// 阻止默认行为
		// const stopProgapation = (el) => {
		// 	if(map.value){
		// 		el.addEventListener('touchstart', (e) => {e.stopPropagation()}, { passive: false });
		// 		el.addEventListener('touchmove', (e) => {e.stopPropagation()}, { passive: false });
		// 		el.addEventListener('touchend', (e) => {e.stopPropagation()}, { passive: false });
		// 	}
		// };
		// stopProgapation(mapRef.value);
		// stopProgapation(listRef.value);
	})
</script>

<style lang="scss" scoped>
	.add-sec-scope-page{
		position: relative;
		height: 100vh;
		display: flex;
		flex-direction: column;
		
		.map-container {
			flex: 1;
			height: calc(100vh - 600upx);
		}
		
		.footer{
			position: relative;
			z-index: 999;
			background-color: #fff;
			height: 600upx;
			
			.list{
				width: 100%;
				height: calc(100% - 44px);
				overflow-y: auto;
				padding-bottom: 100upx;
			}
		}
	}
</style>
<style lang="scss">
	.search{
		.van-search{
			// padding: 0;
		}
	}
	
	
	.address-item {
		padding: 24rpx 30rpx;
		background: #fff;
		border-bottom: 1px solid #f5f5f5;
		
		&:active {
			background-color: #f8f8f8;
		}
		
		.title {
			font-size: 32rpx;
			font-weight: 500;
			color: #333;
			margin-bottom: 8rpx;
			line-height: 1.4;
		}
		
		.address {
			font-size: 26rpx;
			color: #999;
			line-height: 1.4;
		}
	}
</style>